/**
 * 
 */
package com.hector.meinewerk.client.view.widget.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hector.meinewerk.client.R;
import com.hector.meinewerk.client.view.common.ProductDetailActivity;
import com.hector.meinewerk.model.Product;
import com.hector.meinewerk.utils.ImageLoader;

public class ProductView extends LinearLayout {
	// Context
	private Context mContext;

	// View
	private ImageView mImgAvatar;
	private TextView mTxtName;

	// Variable
	private Product mProduct = new Product();
	private ImageLoader mImageLoader;

	public ProductView(Context context) {
		super(context);
		mContext = context;
		mImageLoader = new ImageLoader(mContext);
		setupViews();
	}
	
	public ProductView(Context context, Product product) {
		super(context);
		mContext = context;
		mImageLoader = new ImageLoader(mContext);
		setupViews();
		setProduct(product);
	}
	
	private void setupViews(){
		LayoutInflater inflater = LayoutInflater.from(mContext);
		inflater.inflate(R.layout.item_product, this, true);
		
		this.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				System.out.println("oooooooooo: "+mProduct.getName());
				Product.setCurrentProduct(mProduct);
				openProductDetailActivity();
			}
		});
		mImgAvatar = (ImageView) findViewById(R.id.image_product);
		mTxtName = (TextView) findViewById(R.id.product_name);
	}
	
	public void setProduct(Product product) {
		if(product == null)
			return;
		
		this.mProduct = product;
		updateUI();
	}
	
	private void updateUI(){
//		mTxtName.setText(mProduct.getName());
		mTxtName.setText(String.valueOf(mProduct.getPrice()));
		if(mProduct.getImage() != null){
			if(!TextUtils.isEmpty(mProduct.getImage()[0])){
				mImageLoader.DisplayImage(mProduct.getImage()[0], mImgAvatar);
			}
		}
		if(TextUtils.isEmpty(mProduct.getId())){
			this.setVisibility(View.INVISIBLE);
		} else{
			this.setVisibility(View.VISIBLE);
		}
	}
	
	private void openProductDetailActivity(){
		Intent intent = new Intent(mContext, ProductDetailActivity.class);
		intent.putExtra(ProductDetailActivity.KEY_PRODUCT_ID, mProduct.getId());
		mContext.startActivity(intent);
	}
}
